package funcs

import (
	"archive/zip"
	"io/ioutil"
	"os"

	"github.com/axgle/mahonia"
)

//zip解压缩
//zipFile=zip压缩文件路径，outPaht=解压目录
func DeZip(zipFile, outPath string) error {
	r, err := zip.OpenReader(zipFile)
	if err != nil {
		return err
	}
	defer r.Close()
	os.MkdirAll(outPath, 766)
	for _, f := range r.File {
		ec := mahonia.NewDecoder("gbk")
		f.Name = ec.ConvertString(f.Name)
		rc, err := f.Open()
		defer rc.Close()
		if err != nil {
			return err
		}
		if outPath != "" {
			f.Name = outPath + "/" + f.Name
		}
		if f.FileInfo().IsDir() {
			os.MkdirAll(f.Name, 766)
			continue
		}
		print(f.Name, "\n")
		zf, err := os.Create(f.Name)
		defer zf.Close()
		if err != nil {
			return err
		}
		bt, err := ioutil.ReadAll(rc)
		if err != nil {
			return err
		}
		if _, e := zf.Write(bt); e != nil {
			return e
		}
	}
	return nil
}
